/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bcc.airlines.database;

import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;

/**
 *
 * 
 */
public class DAO<T> {

    private final Session session;
    private Transaction transaction;
    private Class classe;

    public DAO() {
        this.session = getSession();
    }

    public DAO(Class classe) {
        this.session = getSession();
        this.classe = classe;
    }

    private Session getSession() {
        return DatabaseUtil.getSessionFactory().openSession();
    }

    public void beginTransaction() {
        this.transaction = this.session.beginTransaction();
    }

    public void commit() {
        this.transaction.commit();
        this.transaction = null;
    }

    public boolean hasTransaction() {
        return this.transaction != null;
    }

    public void rollback() {
        this.transaction.rollback();
        this.transaction = null;
    }

    public void close() {
        this.session.close();
    }

    public void add(T u) {
        beginTransaction();
        this.session.save(u);
        commit();
    }

    public List<T> list() {
        return this.session.createCriteria(this.classe).list();
    }

    public void rm(T u) {
        beginTransaction();
        this.session.delete(u);
        commit();
    }

    public void up(T u) {
        beginTransaction();
        this.session.merge(u);
        commit();
    }

    public Object get(Serializable obj) {
        return this.session.load(this.classe, obj);
    }

    public List<T> criterionSearch(Criterion restrinction) {
        return this.session.createCriteria(this.classe).add(restrinction).list();
    }
}
